package com.example.javaee_blog.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.util.UUID;
@Slf4j
public class SecurityUtils {
    public static String encrypt(String password){
        String mdSStr = DigestUtils.md5DigestAsHex(password.getBytes());
        //随机盐值
        String salt = UUID.randomUUID().toString().replace("-","");
        //密文：盐值 + 明文 加密
        String securityPassword = DigestUtils.md5DigestAsHex((salt+password).getBytes());
        // salt + 密文 存储在数据库
        String finalPassword = salt + securityPassword;
        return finalPassword;
    }

    public static boolean verify(String password, String sqlPassword){
        // sqlPassword: salt + 密文 存储在数据库
        if(sqlPassword == null || sqlPassword.length()!=64){
            log.error("数据库中密码格式不对");
            return false;
        }
        String salt = sqlPassword.substring(0, 32);
        String securityPassword = DigestUtils.md5DigestAsHex((salt+password).getBytes());
        return (salt+securityPassword).equals(sqlPassword);
    }
}
